# encoding: utf-8
# @File  : init_db.py
# @Author: shaoyun
# @Date  :  2025/05/11

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from app.db.mysql import Base, engine, SessionLocal
from app.models.user import User, UserRole

from app.core.security import get_password_hash
from loguru import logger
import uuid


def create_admin_user():
    """创建默认管理员用户"""
    db = SessionLocal()
    try:
        # 检查是否已存在管理员
        admin = db.query(User).filter(User.username == "admin2").first()
        if not admin:
            admin = User(
                id=str(uuid.uuid4()),
                username="admin2",
                email="admin2@example.com",
                hashed_password=get_password_hash("admin123"),
                role=UserRole.ADMIN,
                is_active=True
            )
            db.add(admin)
            db.commit()
            logger.info("Default admin user created (username: admin, password: admin123)")
            logger.warning("Please change the default password immediately!")
        else:
            logger.info("Admin user already exists")

    except Exception as e:
        logger.error(f"Error creating admin user: {e}")
        db.rollback()
    finally:
        db.close()





if __name__ == "__main__":
    # 如果是第一次运行或想重置数据库，设置为True
    create_admin_user()